package com.ws.controller;

import com.alibaba.fastjson.JSONObject;
import com.ws.bean.Depart;
import com.ws.bean.Employee;
import com.ws.bean.Log;
import com.ws.service.DepartService;
import com.ws.service.EmployeeService;
import com.ws.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Controller
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DepartService departService;

    @RequestMapping("/uploadPhoto")
    public String uploadPhoto(MultipartFile file, HttpServletRequest req) {
        log.info("请求：/uploadPhoto" + ",更换头像功能");
        System.out.println(file);
        String filename = file.getOriginalFilename();
        System.out.println("上传的文件名:"+filename);

        String path = req.getServletContext().getRealPath("upload/");
        System.out.println(path);

        String photo="upload/"+new SimpleDateFormat("YYYYMMddHHmmss").format(new Date()) + "_" + filename;
        filename = path + new SimpleDateFormat("YYYYMMddHHmmss").format(new Date()) + "_" + filename;
        System.out.println("保存到服务器的文件名:"+filename);
        File dest = new File(filename);
        try {

            file.transferTo(dest);//把文件上传到服务器的upload目录下

            //把上传到服务器的路径：upload/文件名 保存到数据库登录用户photo字段中
            //eid和path1
            Employee emp = (Employee)req.getSession().getAttribute("emp");
            emp.setPhoto(photo);
            employeeService.updatePhoto(emp.getEid(), photo);

        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return "main.jsp";
    }


    @RequestMapping("/updatePwd")
    public String updatePwd(String epass, String repass, int eid) {
        System.out.println(epass + "\t" + repass + "\t" + eid);
        if (epass.equals(repass)) {
            employeeService.updatePwd(eid, epass);
            return "redirect:index.html";
        } else {
            return "redirect:index.html";
        }
    }

//    @RequestMapping("/login")
//    public String login(String ename, String epass, HttpSession session) {
//        //1.获取请求参数
//        System.out.println(ename + "\t" + epass);
//
//        //2.调用service
//        Employee emp = employeeService.login(ename, epass);
//        System.out.println(emp);
//
//        if (emp != null) {
//            //3.共享数据
//            session.setAttribute("emp", emp);
//            //4.响应
//            return "redirect:/main.jsp";
//        } else {
//            return "index.html";
//        }
//
//    }
    @RequestMapping("/login")
    public String login(HttpServletRequest request, String ename, String epass, HttpSession session) {

        // 1 获取请求参数
        System.out.println(ename + "\t" + epass);
        // 2 调用Service
        Employee emp = employeeService.login(ename, epass);
        System.out.println(emp);

        {
            /*
             * 获取操作日志信息，转换成json格式的数据
             */
            System.out.println(session.getId());
            String ip = IPUtils.getIpAddr(request);
            LocalDateTime datetime = LocalDateTime.now();
            String reqName = request.getRequestURI();
            StringBuffer reqURL = request.getRequestURL();
            Log log = new Log(session.getId(), "login", "index.html", ip, datetime, emp.getEid(), reqName, reqURL);
            System.out.println(log);
            Object json = JSONObject.toJSON(log);
            System.out.println(json);

            String path = session.getServletContext().getRealPath("/logs/oa.log");
            System.out.println(path);
            /*
             *  把操作日志信息写入到日志文件中s
             */
            try {
                FileWriter fw = new FileWriter(path, true);
                fw.write(json.toString());
                fw.write("\n");
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (emp != null) {// 登录成功
            // 3 共享数据
            session.setAttribute("emp", emp);
//            List<Depart> depts = departService.findAllDepart(0);
//            session.setAttribute("depts", depts);
            // 4 响应
            return "main.jsp";
        } else {
            return "index.html";
        }
    }


    @RequestMapping("/findByPage")
    public String findByPage(String estatus, int page, int size, Model model) {
        System.out.println(estatus + "\t" + page + "\t" + size);
        //调用service
        List<Employee> employees = employeeService.findByPage(estatus, page, size);
        System.out.println(employees);
        // 查询总行数
        int lines = employeeService.totalLine(estatus);
        // 计算总页数
        int pages = lines%size==0?lines/size:lines/size+1;

        //共享数据
        model.addAttribute("employees", employees);
        model.addAttribute("lines", lines);
        model.addAttribute("pages", pages);
        model.addAttribute("page", page);
        model.addAttribute("estatus", estatus);

        //响应
        return "user.jsp";
    }

    @RequestMapping("/addEmp")
    public String addEmp(Employee employee) {

        System.out.println(employee);
        //调用service
        employeeService.addEmp(employee);
        //响应
        return "findByPage?estatus=0&page=1&size=4";

    }


    @RequestMapping("findByEid")
    public String findByEid(String eid, Model model) {

        //调用service层
        Employee employee = employeeService.findByEid(eid);
        // 共享数据
        model.addAttribute("employee", employee);

        return "editUser.jsp";
    }

    @RequestMapping("editUser")
    public String editUser(Employee employee) {
        System.out.println("修改员工");
        System.out.println(employee);
        employeeService.editUser(employee);
        return "findByPage?estatus=0&page=1&size=4";
    }

    @RequestMapping("updateEmp")
    public String updateEmp(int estatus, int eid) {

        //调用service层，如果是离职，则添加离职时间
        if (estatus == 1) {
            employeeService.updateEmp1(estatus, eid);
        }
        //如果是重新入职，则更新入职时间，并删除离职时间
        else {
            employeeService.updateEmp2(estatus, eid);
        }

        //离职，estatus=1，离职后查询在职；返聘反之
        estatus = estatus == 1? 0 : 1;
        return "findByPage?estatus=" + estatus + "&page=1&size=4";
    }


    @RequestMapping("findByName")
    public String findByName(String realname, String estatus, Model model) {
        System.out.println(realname);
        List<Employee> employees = employeeService.findByName(realname, estatus);
        // 查询总行数
//        int lines = employeeService.totalLine2(realname, estatus);
//        model.addAttribute("lines", lines);
        model.addAttribute("employees", employees);
        model.addAttribute("like", 1);//用来判断是否为模糊查询
        return "user.jsp";
    }


    //注销登录
    @RequestMapping("/logout")
    public String logout(HttpSession session, SessionStatus sessionStatus) {
        System.out.println("logout");

        //session失效
        session.removeAttribute("emp");
        session.removeAttribute("departs");
        session.removeAttribute("employees");
        session.removeAttribute("depart");

        session.invalidate();
        sessionStatus.setComplete();
        return "redirect:/login";
    }

}
